import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class _103 {
    static class Solution1 {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            preOrder(root, res, 0);
            for (int i = 1; i < res.size(); i += 2) {
                Collections.reverse(res.get(i));
            }
            return res;
        }

        public void preOrder(TreeNode root, List<List<Integer>> res, int lv) {
            if (root == null) return;
            if (res.size() == lv) {
                res.add(new ArrayList<>());
            }
            res.get(lv).add(root.val);
            preOrder(root.left, res, lv + 1);
            preOrder(root.right, res, lv + 1);
        }
    }

    static class Solution2 {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            boolean isLeft = true;
            if (root == null) {
                return res;
            }
            List<TreeNode> cur = new ArrayList<>();
            cur.add(root);
            while (cur.size() > 0) {
                List<Integer> resItem = new ArrayList<>();
                List<TreeNode> next = new ArrayList<>();
                for (TreeNode node : cur) {
                    resItem.add(node.val);
                    if (node.left != null) next.add(node.left);
                    if (node.right != null) next.add(node.right);
                }
                res.add(resItem);
                if (!isLeft) {
                    Collections.reverse(resItem);
                }
                isLeft = !isLeft;
                cur = next;
            }
            return res;
        }
    }
}
